import {
  PlatformLocation, Location,APP_BASE_HREF, LocationChangeListener,
  LocationStrategy
} from "@angular/common";
import {Injectable, Optional, Inject} from "@angular/core";

@Injectable()
export class QueryAndHashLocationStrategy extends LocationStrategy{
  private _baseHref: string = '';
  constructor(
    private _platformLocation: PlatformLocation,
    @Optional() @Inject(APP_BASE_HREF) _baseHref?: string) {
    super();
    if (_baseHref != null) {
      this._baseHref = _baseHref;
    }
  }

  onPopState(fn: LocationChangeListener): void {
    this._platformLocation.onPopState(fn);
    this._platformLocation.onHashChange(fn);
  }

  getBaseHref(): string { return this._baseHref; }

  path(includeHash: boolean = false): string {
    // the hash value is always prefixed with a `#`
    // and if it is empty then it will stay empty

    let path = this._platformLocation.hash;
    //if (path == null) path = '#';
    if(!path){
      path=Location.normalizeQueryParams(this._platformLocation.search);
      path=path?"/"+path:"#";
    }
    console.log("invoke path:"+path);
    return path.length > 0 ? path.substring(1) : path;
  }

  prepareExternalUrl(internal: string): string {
    const url = Location.joinWithSlash(this._baseHref, internal);
    console.log("invoke url:"+url)
    return url.length > 0 && url!="/" ? ('?#' + url) : url;
  }

  pushState(state: any, title: string, path: string, queryParams: string) {
    let url: string|null =
      this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
    if (url.length == 0) {
      url = this._platformLocation.pathname;
    }
    this._platformLocation.pushState(state, title, url);
  }

  replaceState(state: any, title: string, path: string, queryParams: string) {
    let url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
    if (url.length == 0) {
      url = this._platformLocation.pathname;
    }
    this._platformLocation.replaceState(state, title, url);
  }

  forward(): void { this._platformLocation.forward(); }

  back(): void { this._platformLocation.back(); }
}
